package at.ac.tuwien.swa.sparrow.util

import com.codahale.jerkson.Json
import java.io.IOException
import org.springframework.http.converter.{HttpMessageNotWritableException, HttpMessageNotReadableException, HttpMessageConverter}
import org.springframework.http.{MediaType, HttpOutputMessage, HttpInputMessage}
import scala.collection.JavaConversions._

class MappingJerksonHttpMessageConverter[T](val supportedMediaType: MediaType) extends HttpMessageConverter[T] {

	override def canRead(clazz: Class[_], mediaType: MediaType) = Json canDeserialize Manifest.classType(clazz)

	override def canWrite(clazz: Class[_], mediaType: MediaType) = Json canSerialize Manifest.classType(clazz)

	override def getSupportedMediaTypes = List(supportedMediaType)

	@throws(classOf[IOException])
	@throws(classOf[HttpMessageNotReadableException])
	override def read(clazz: Class[_ <: T], inputMessage: HttpInputMessage): T = Json parse inputMessage.getBody

	@throws(classOf[IOException])
	@throws(classOf[HttpMessageNotWritableException])
	override def write(t: T, contentType: MediaType, outputMessage: HttpOutputMessage) {
		Json generate(t, outputMessage.getBody)
	}

}
